package com.zengge.zbc.controller;

import com.zengge.zbc.dto.Result;
import com.zengge.zbc.exception.ErrorCode;
import com.zengge.zbc.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class ExceptionController {


    private final static Logger logger = LoggerFactory.getLogger(ExceptionController.class);

    @ExceptionHandler({ServiceException.class})
    @ResponseBody
    public Result<String> handlerServiceException(ServiceException ex){
        return Result.create(ex);
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Result<String> serverException(Exception e) {
        logger.error(e.getMessage());
        if (e instanceof ServiceException) {
            return  Result.create((ServiceException) e);
        }
        return Result.create(new ServiceException(ErrorCode.SERVICE_ERROR));
    }

}
